<template>
  <div class='upload-wrapper__drag'>
    <el-upload v-show="isUploadShow" class="upload-drag" drag :disabled="disabled" :file-list="fileList" :before-upload="handleFileBefore"
      :on-success="handleFileSuccess" :on-error="handleFileError" :on-exceed="handleExceed" :limit="limit"
      :multiple="multiple" :show-file-list="false" :action="uploadFileUrl" :headers="headers">
      <i class="el-icon-upload"></i>
      <slot name="text"></slot>
      <slot name="tip"></slot>
    </el-upload>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li class="ele-upload-list__item-content flex gap-10 " :key="file.url" v-for="(file, index) in fileList">
        <el-link :underline="false" @click="filePreview(file)" type="primary">
          <span class="el-icon-document white"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action" v-show="!deleteFlag">
          <el-link  :underline="false" @click="handleDelete(index)" type="danger">删除</el-link>
        </div>
      </li>
    </transition-group>
    <el-dialog title="文件预览" class="large_dialog" top="10px" :visible.sync="dialogVisablefilePreview" append-to-body>
      <file-preview :fileName="fileUrl" />
    </el-dialog>
  </div>
</template>

<script>
import { get } from '@/utils/auth'
import FilePreview from '@/components/FilePreview'
import { mapState } from 'vuex'

export default {
  props: {
    value: [String, Object, Array],
    // 文件上传数量限制
    limit: {
      type: Number,
      default: 5
    },
    isUploadShow:{
      type: Boolean,
      default: true
    },
    fileSize: {
      type: Number,
      default: 100
    },
    fileType: {
      type: Array,
      default: () => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'mp4'],
    },
    disabled: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    deleteFlag: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + get('admin_token'),
      },
      // 上传文件列表
      uploadList: [],
      // 文件列表
      fileList: [],
      // 文件数量
      fileCount: 0,
      dialogVisablefilePreview: false,
      fileUrl: ''
    };
  },
  computed: {
    ...mapState('config', ['inFilePrefix']),
  },
  watch: {
    value: {
      handler(val) {
        console.log(val)
        if (val) {
          if (typeof val === 'string') {
            let parts = val.split('/');
            this.fileList = [
              {
                name: parts[parts.length - 1],
                url: val
              }
            ]
          } else {
            this.fileList = val.map(item => ({
              name: item,
              url: item
            }))
          }

        }
      },
      immediate: true
    }
  },
  methods: {
    // 上传文件之前检验文件格式和文件大小
    handleFileBefore(file) {
      if (this.fileType) {
        const fileName = file.name.split('.')
        const fileExt = fileName[fileName.length - 1];
        if (this.fileType.indexOf(fileExt) === -1) {
          this.$message.warning('文件格式不正确')
          return false
        }
      }
      // 检测文件大小
      if (this.fileSize) {
        const currentFileSize = file.size / 1024 / 1024
        if (currentFileSize > this.fileSize) {
          this.$message.warning(`文件大小不能超过${this.fileSize}MB`)
          return false
        }
      }

      this.fileCount++
      return true
    },
    // 文件超出限制
    handleExceed() {
      this.$message.warning(`最多只能上传${this.limit}个文件`)
    },
    // 上传文件失败
    handleFileError() {
      this.$message.error('上传失败')
    },
    // 上传成功
    handleFileSuccess(res) {
      if (200 === res.code) {
        const resp = res.data
        console.log(resp)
        this.$emit('change', resp)
        this.uploadList.push({ name: resp.name, url: resp.url })
        this.uploadSuccessFull()
      }
    },
    // 文件上传完成
    uploadSuccessFull() {
      if (this.fileCount > 0 && this.uploadList.length === this.fileCount) {
        this.fileList = this.fileList.concat(this.uploadList)
        this.$emit('uploadSuccess', this.fileList)
        this.uploadList = []
        this.fileCount = 0
        this.$message.success('上传成功')
      }
    },
    // 点击删除文件
    handleDelete(index) {
      if(this.deleteFlag){
        return false
      }
      this.fileList.splice(index, 1)
      this.$emit('remove', this.fileList)
    },
    // 获取文件名称
    getFileName(name) {
      console.log(name)
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    filePreview(file) {
      this.fileUrl = this.inFilePrefix + file.url
      console.log(this.fileUrl)
      this.dialogVisablefilePreview = true
    }
  },
  created() {
  },
  mounted() {

  },
  components: {
    FilePreview,
  },
}
</script>